
import com.anhdt.model.User;
import com.anhdt.vo.UserVO;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ADIndex extends BaseService {

    final static String ROOT = "ROOT";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String username = request.getParameter("username");
            String password = request.getParameter("password");

            User userSV = User.getInstance();
            UserVO user = userSV.checkLogin(username, password);

            ArrayList<String> error = new ArrayList<>();
            if (user == null) {
                error.add("Sai tên đăng nhập hoặc mật khẩu");
            } else {
               HttpSession session  = request.getSession();
               session.setAttribute("user", user);
               gotoPage("home", request, response);
               return;
            }
            request.setAttribute("error", error);

            gotoPage("index", request, response);
        } catch (SQLException ex) {
            Logger.getLogger(ADIndex.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void gotoPage(String name, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        commonResponse(request, response);
        RequestDispatcher requestDispatcher;
        requestDispatcher = request.getRequestDispatcher("admin_page/" + name + ".jsp");
        requestDispatcher.forward(request, response);
    }

    public void commonResponse(HttpServletRequest request, HttpServletResponse response) {
        request.setAttribute(ROOT,  getServletContext().getInitParameter("root"));
    }
}
